package com.yilong.springcloudalibabanacos.sys.controller;

import com.yilong.springcloudalibabanacos.sys.utils.RedissonUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @version 1.0.0
 * @项目名称: com.yilong.springcloudalibabanacos.sys.controller
 * @类名称: RedissionController
 * @类描述: #服务类
 * @功能描述: 功能描述
 * @创建人: WYL
 * @创建时间: 2022-12-11 17:19:11
 * @修改备注: 对该类进行修改时备注该处
 * @修改记录: 修改时间 修改人员 修改原因
 * -----------------------------------------------------
 * @Copyright (c) 宇信科技-版权所有
 */
@Slf4j
@RequestMapping("redisson")
@RestController
public class RedissonController {

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private RedissonUtil redissonUtil;

    @RequestMapping("getRateLimiter")
    public String getRateLimiter(String name) {
        RLock lock = redissonClient.getLock(name);
        try {
            boolean res = lock.tryLock(100, 20, TimeUnit.SECONDS);
            log.info("获取锁:{},状态:{}", name, res);
            Thread.sleep(6000);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.lock();
            log.info("释放锁:{}", name);
        }
        return "成功!";
    }

    @RequestMapping("/get1")
    public  String  get1(){
        try{
            log.info("============={} 线程访问开始============",Thread.currentThread().getName());
            //TODO 尝试获取锁，等待5秒，自己获得锁后一直不解锁则7秒后自动解锁
            //boolean lock = redissonUtil.tryLock("lock1", TimeUnit.SECONDS, 5L, 7L);
            //进行5s的尝试时间，如果失败则返回false， 还可以设置锁过期时间，如果设置会导致看门狗无效
            boolean lock = redissonUtil.tryLock("lock1", TimeUnit.SECONDS, 5L);
            if (lock) {
                log.info("线程:{}，获取到了锁",Thread.currentThread().getName());
                Thread.sleep(100);
                log.info("======获得锁后进行相应的操作======" + Thread.currentThread().getName());
                //redissonUtil.unlock("lock1");  //释放锁
                log.info("=================" + Thread.currentThread().getName());
            }
        }catch (Exception e){
            log.info("错误信息：{}",e.toString());
            log.info("线程：{} 获取锁失败",Thread.currentThread().getName());
        }
        return "success";
    }


}
